﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using lt_pmbc_001.Forms;
using lt_pmbc_001.Helpers;
using lt_pmbc_001.DAL;
using System.Media;
using lt_pmbc_001.DTO;
using System.Threading;
using System.Text.RegularExpressions;

namespace lt_pmbc_001
{
    public partial class MainForm : Office2007Form
    {
        private delegate void UpdateLSBCDel(DataRow row);
        private CommunicationManager comm = new CommunicationManager();
        private string transType = string.Empty;
        private SoundPlayer simpleSound;

        public MainForm()
        {
            InitializeComponent();
            LoadDiaDiem(null, null);
            LoadValues();
            SetDefaults();
            SetControlState();
            LoadLichSuBaoChay();
            comm.Handler += DataReceived;
            simpleSound = new SoundPlayer(Application.StartupPath + @".\Sound\alert.wav");
            dtgvLSBC.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(dtgvLSBC_EditingControlShowing);
            this.tabControl1.TabPages.Remove(this.tabPage3);
        }

        private void dtgvLSBC_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            //here we will add the combo box's selected event changed
            ComboBox cmbBox;
            if (dtgvLSBC.CurrentCell.ColumnIndex == 8)
            {
                cmbBox = e.Control as ComboBox;
                if (cmbBox == null)
                    return;
                cmbBox.SelectedIndexChanged += cmbBox_SelectedIndexChanged;
            }
        }

        /// <summary>
        /// This will display value of Select values of Combo Box which is DataGridView
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void cmbBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            var objBUS = new LichSuBaoChayDAL(GlobalVariables.g_strPath);
            var lsbc = new LichSuBaoChayDTO
            {
                ID = int.Parse(this.dtgvLSBC.Rows[dtgvLSBC.CurrentRow.Index].Cells[0].Value.ToString())
            };

            ComboBox cmbBox = (ComboBox)sender;
            switch (cmbBox.Text)
            {
                case "Chưa xử lý":
                    this.dtgvLSBC.Rows[dtgvLSBC.CurrentRow.Index].DefaultCellStyle.BackColor = Color.Crimson;
                    this.dtgvLSBC.Rows[dtgvLSBC.CurrentRow.Index].DefaultCellStyle.ForeColor = Color.White;
                    lsbc.TinhTrang = "Chưa xử lý";
                    break;

                case "Đang xử lý":
                    this.dtgvLSBC.Rows[dtgvLSBC.CurrentRow.Index].DefaultCellStyle.BackColor = Color.Green;
                    this.dtgvLSBC.Rows[dtgvLSBC.CurrentRow.Index].DefaultCellStyle.ForeColor = Color.White;
                    lsbc.TinhTrang = "Đang xử lý";
                    break;

                case "Đã xử lý":
                    this.dtgvLSBC.Rows[dtgvLSBC.CurrentRow.Index].DefaultCellStyle.BackColor = Color.White;
                    this.dtgvLSBC.Rows[dtgvLSBC.CurrentRow.Index].DefaultCellStyle.ForeColor = Color.Black;
                    lsbc.TinhTrang = "Đã xử lý";
                    break;
            }
            var result = objBUS.Update(lsbc);
        }

        private void LoadLichSuBaoChay()
        {
            dtgvLSBC.Rows.Clear();
            var objBUS = new LichSuBaoChayDAL(GlobalVariables.g_strPath);
            var ds = objBUS.SelectAll();
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    // Insert new lsbc at index 0
                    object[] values = new object[9];
                    values[0] = row["ID"].ToString(); // ID
                    values[1] = row["IDChiTietDiaDiem"].ToString(); // ID
                    values[2] = row["DiaDiem"].ToString(); // Dia diem
                    values[3] = row["DiaChi"].ToString(); // Dia chi
                    values[4] = row["Phong"].ToString(); // Phong
                    values[5] = row["Lau"].ToString(); // Lau
                    values[6] = row["ToaNha"].ToString(); // Toa nha
                    values[7] = row["NgayBaoChay"].ToString(); // Ngay bao chay
                    values[8] = row["TinhTrang"].ToString(); // Tinh trang

                    dtgvLSBC.Rows.Add(values);
                }
                dtgvLSBC.ClearSelection();
            }
        }

        /// <summary>
        /// Read content of SMS
        /// The example content of SMS is as:
        /// <CR><LF>+CMGR: "REC UNREAD","+84929047589",,"07/05/15,09:32:05+28"  
        /// <CR><LF>Content
        /// <CR><LF> 
        /// <CR><LF>OK
        /// <CR><LF> 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DataReceived(object sender, EventArgs e)
        {
            var evt = (TransferDataEvent)e;
            var compSMS = evt.Data.Split(new char[] { '#' });

            // Get time
            var time = compSMS[0].Trim();
            var timeVal = DateTime.Now;
            //if (!DateTime.TryParse(compSMS[0].Trim(), out timeVal))
            //{
            //    timeVal = DateTime.Now;
            //}
            // Get content
            var idChiTietDiaDiem = compSMS[1].Trim().ToUpper();

            // Checking if diadiem is existent
            var objBUS = new ChiTietDiaDiemDAL(GlobalVariables.g_strPath);
            var ds = objBUS.SelectByID(idChiTietDiaDiem);

            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                // Insert new lsbc
                var row = ds.Tables[0].Rows[0];
                var lsbc = new LichSuBaoChayDTO
                {
                    IDChiTietDiaDiem = idChiTietDiaDiem,
                    NgayBaoChay = timeVal,
                    TinhTrang = "Chưa xử lý"
                };
                // Insert new lich su bao chay
                var objBUS2 = new LichSuBaoChayDAL(GlobalVariables.g_strPath);
                if (objBUS2.Insert(lsbc))
                {
                    // Get id of new lsbc
                    objBUS2 = new LichSuBaoChayDAL(GlobalVariables.g_strPath);
                    ds = objBUS2.RetrieveMaxID();
                    if (ds != null && ds.Tables[0].Rows.Count > 0)
                    {
                        // Select lsbc by id
                        row = ds.Tables[0].Rows[0];
                        objBUS2 = new LichSuBaoChayDAL(GlobalVariables.g_strPath);
                        ds = objBUS2.SelectByID(int.Parse(row["MAXID"].ToString()));
                        row = ds.Tables[0].Rows[0];
                        UpdateListLSBC(row);
                    }
                }
            }
            else
            {
                //MessageBoxEx.Show("Thiết bị ứng với id = "  + idChiTietDiaDiem + " không tồn tại trong cơ sở dữ liệu, mọi thao tác xử lý sẽ được bỏ qua!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

        }

        private void UpdateListLSBC(DataRow row)
        {
            if (dtgvLSBC.InvokeRequired)
            {
                UpdateLSBCDel del = new UpdateLSBCDel(UpdateListLSBC);
                dtgvLSBC.Invoke(del, new object[] { row });
                return;
            }

            // Insert new lsbc at index 0
            object[] values = new object[9];
            values[0] = row["ID"].ToString(); // ID
            values[1] = row["IDChiTietDiaDiem"].ToString(); // ID
            values[2] = row["DiaDiem"].ToString(); // Dia diem
            values[3] = row["DiaChi"].ToString(); // Dia chi
            values[4] = row["Phong"].ToString(); // Phong
            values[5] = row["Lau"].ToString(); // Lau
            values[6] = row["ToaNha"].ToString(); // Toa nha
            values[7] = row["NgayBaoChay"].ToString(); // Ngay bao chay
            values[8] = row["TinhTrang"].ToString(); // Tinh trang

            dtgvLSBC.Rows.Insert(0, values);

            simpleSound.Play();
            notifyIcon1.ShowBalloonTip(30000, "Thông báo cháy", "Nhấn vào để xem chi tiết", ToolTipIcon.Error);
        }

        /// <summary>
        /// Method to initialize serial port
        /// values to standard defaults
        /// </summary>
        private void SetDefaults()
        {
            cbxPort.SelectedIndex = 0;
            cbxBaudRate.SelectedText = "9600";
            cbxParity.SelectedIndex = 0;
            cbxStopBit.SelectedIndex = 1;
            cbxDataBit.SelectedIndex = 1;
        }

        /// <summary>
        /// methos to load our serial
        /// port option values
        /// </summary>
        private void LoadValues()
        {
            var lst = comm.GetPortNameValues();
            cbxPort.Items.Clear();
            foreach (var str in lst)
            {
                cbxPort.Items.Add(str);
            }

            lst = comm.GetParityValues();
            cbxParity.Items.Clear();
            foreach (var str in lst)
            {
                cbxParity.Items.Add(str);
            }

            lst = comm.GetStopBitValues();
            cbxStopBit.Items.Clear();
            foreach (var str in lst)
            {
                cbxStopBit.Items.Add(str);
            }
        }

        /// <summary>
        /// method to set the state of controls
        /// when the form first loads
        /// </summary>
        private void SetControlState()
        {
            btnClosePort.Enabled = false;
        }

        private void btnThem_Click(object sender, EventArgs e)
        {
            FrmThemDiaDiem frm = new FrmThemDiaDiem();
            frm.Handler += LoadDiaDiem;
            frm.ShowDialog();
        }

        public void LoadDiaDiem(object sender, EventArgs e)
        {
            dtgvData.Rows.Clear();
            var objBUS = new DiaDiemDAL(GlobalVariables.g_strPath);
            var ds = objBUS.SelectAll();

            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                var row = ds.Tables[0].Rows[i];
                object[] values = new object[4];
                values[0] = i + 1;
                values[1] = row["ID"].ToString();
                values[2] = row["DiaDiem"].ToString();
                values[3] = row["DiaChi"].ToString();
                dtgvData.Rows.Add(values);
            }    
        }

        private void dtgvData_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dtgvData.SelectedRows == null || dtgvData.SelectedRows.Count == 0)
            {
                return;
            }
            var ID = int.Parse(dtgvData.SelectedRows[0].Cells["ID"].Value.ToString());
            FrmThemDiaDiem frm = new FrmThemDiaDiem(ID);
            frm.Handler += LoadDiaDiem;
            frm.ShowDialog();
        }

        private void ShowMap()
        {
            FrmHienThiMap frm = new FrmHienThiMap(dtgvData.SelectedRows[0].Cells["DiaChi"].Value.ToString());
            frm.ShowDialog();
        }

        private void btnXemBanDo_Click(object sender, EventArgs e)
        {
            if (dtgvData.SelectedRows == null || dtgvData.SelectedRows.Count == 0)
            {
                return;
            }
            Thread thread = new Thread(new ThreadStart(ShowMap));
            thread.Start();    
        }

        private void btnXoa_Click(object sender, EventArgs e)
        {
            if (dtgvData.SelectedRows == null || dtgvData.SelectedRows.Count == 0)
            {
                return;
            }
            var ID = int.Parse(dtgvData.SelectedRows[0].Cells["ID"].Value.ToString());
            var objBUS = new DiaDiemDAL(GlobalVariables.g_strPath);
            if (objBUS.Delete(ID))
            {
                MessageBoxEx.Show("Xóa dữ liệu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                LoadDiaDiem(null, null);
            }
            else
            {
                MessageBoxEx.Show("Xóa dữ liệu thất bại", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnCapNhat_Click(object sender, EventArgs e)
        {
            if (dtgvData.SelectedRows == null || dtgvData.SelectedRows.Count == 0)
            {
                return;
            }
            FrmCapNhatThietBi frm = new FrmCapNhatThietBi(int.Parse(dtgvData.SelectedRows[0].Cells["ID"].Value.ToString()));
            frm.ShowDialog();
        }

        private void btnOpenPort_Click(object sender, EventArgs e)
        {
            btnOpenPort.Enabled = false;
            btnClosePort.Enabled = true;

            cbxPort.Enabled = false;
            cbxParity.Enabled = false;
            cbxStopBit.Enabled = false;
            cbxDataBit.Enabled = false;
            cbxBaudRate.Enabled = false;

            comm.PortName = cbxPort.Text;
            comm.Parity = cbxParity.Text;
            comm.StopBits = cbxStopBit.Text;
            comm.DataBits = cbxDataBit.Text;
            comm.BaudRate = cbxBaudRate.Text;

            // Open port to transfer data
            if (comm.OpenPort())
            {
                // Select SMS message format (text)
                comm.WriteData("AT+CMGF=1\r");

                Thread.Sleep(200);

                // New SMS message indication
                comm.WriteData("AT+CNMI=2,1,0,0,0\r");

                Thread.Sleep(200);

                // Save SMS setting
                comm.WriteData("AT+CSAS\r");

                Thread.Sleep(200);

                // Delete SMS at position 1 so that the next SMS received at this position
                comm.WriteData("AT+CMGD=1\r");
            }
        }

        private void btnClosePort_Click(object sender, EventArgs e)
        {
            comm.ClosePort();
            btnOpenPort.Enabled = true;
            btnClosePort.Enabled = false;

            cbxPort.Enabled = true;
            cbxParity.Enabled = true;
            cbxStopBit.Enabled = true;
            cbxDataBit.Enabled = true;
            cbxBaudRate.Enabled = true;
        }

        private void MainForm_Move(object sender, EventArgs e)
        {
            //This code causes the form to not show up on the task bar only in the tray.
            //NOTE there is now a form property that will allow you to keep the application
            //from every showing up in the task bar.
            if (this == null)
            { //This happen on create.
                return;
            }
            //If we are minimizing the form then hide it so it doesn't show up on the task bar
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Hide();
            }
            else
            {
                //any other windows state show it.
                this.Show();
            }
        }

        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Show();
                this.WindowState = FormWindowState.Normal;
            }

            // Activate the form.
            this.Activate();
            this.Focus();
        }

        private void menShowForm_Click(object sender, EventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
            // Activate the form.
            this.Activate();
            this.Focus();
        }

        private void menExitApp_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void notifyIcon1_BalloonTipClicked(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Show();
                this.WindowState = FormWindowState.Normal;
            }

            // Activate the form.
            this.Activate();
            this.Focus();

            // Stop sound
            simpleSound.Stop();

            this.tabControl1.SelectedIndex = 1;
        }

        private void dtgvLSBC_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            switch (dtgvLSBC.Rows[e.RowIndex].Cells[8].Value.ToString())
            {
                case "Chưa xử lý":
                    e.CellStyle.BackColor = Color.Crimson;
                    e.CellStyle.ForeColor = Color.White;
                    break;

                case "Đang xử lý":
                    e.CellStyle.BackColor = Color.Green;
                    e.CellStyle.ForeColor = Color.White;
                    break;

                case "Đã xử lý":
                    e.CellStyle.BackColor = Color.White;
                    e.CellStyle.ForeColor = Color.Black;
                    break;
            }
        }

        private void buttonX1_Click(object sender, EventArgs e)
        {
            if (dtgvLSBC.SelectedRows == null || dtgvLSBC.SelectedRows.Count == 0)
            {
                return;
            }
            Thread thread = new Thread(new ThreadStart(ShowMap));
            thread.Start(); 
        }

        private void btnTestSong_Click(object sender, EventArgs e)
        {
            var msg = "at+csq\r";
            comm.WriteData(msg);
        }

        private void btnXoaLichSu_Click(object sender, EventArgs e)
        {
            var objBUS = new LichSuBaoChayDAL(GlobalVariables.g_strPath);
            if (objBUS.Delete())
            {
                MessageBoxEx.Show("Xóa dữ liệu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                LoadLichSuBaoChay();
            }
            else
            {
                MessageBoxEx.Show("Không thể xóa dữ liệu", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
    }
}
